<?php
/**
 * Created by PhpStorm.
 * User: zhulei
 * Date: 2020/1/24
 * Time: 下午1:29
 */

namespace App\HttpController\Api\Admin;

use App\HttpController\Api\ApiBase;
use App\Model\Admin\AdminModel;
use EasySwoole\Http\Message\Status;
use EasySwoole\Validate\Validate;

class AdminBase extends ApiBase
{
    //public 才会根据协程清除
    public $who;

    //session的cookie的头
    protected $sessionKey = 'adminSession';

    //白名单
    protected $whiteList = [];

    /**
     * OnRequest
     * @param null|string $action
     * @return bool|null
     * @throws \Throwable
     */
    function onRequest(?string $action): ?bool
    {
        if(parent::onRequest($action)){
            //白名单
            if(in_array($action,$this->whiteList)) {
                return true;
            }
            //获取登录信息
            if(!$this->getWho()) {
                $this->writeJson(Status::CODE_NOT_FOUND, '', '登入已过期');
                return false;
            }
            return true;
        }
        return false;
    }

    //获取用户信息
    function getWho()
    {
        if($this->who instanceof AdminModel ){
            return $this->who;
        }
        $sessionKey = $this->request()->getRequestParam($this->sessionKey);
        if (empty($sessionKey)) {
            $sessionKey = $this->request()->getCookieParams($this->sessionKey);
        }
        if (empty($sessionKey)) {
            return null;
        }
        $adminModel = new AdminModel();
        $adminModel->adminSession = $sessionKey;
        $this->who = $adminModel->getOneBySession();
        return $this->who;
    }

    protected function getValidateRule(?string $action): ?Validate
    {
        return null;
    }


}